$.mobileFeedback = function () {
    return{
        id:'',
        data:{
            userData:'',
            page:0,
            pageSize:10,
            totalCount:'',
            feedbackType:[]
        },
        sendData:{
            describe:'',
            feedbackType:'',
            image:[],
            images:[]
        },
        init:function(){
            this.initLayui();
            this.eventListen();
            this.ajaxRequest('/feedback/getMobileInit','get',null,false,function (res) {
                $.mobileFeedback.data.feedbackType = res.feedbackType;
            });

            //初始化获取用户数据
            $('#upload .icon').height($('#upload .icon').width());
            $('.main').css({"padding-bottom":$('.bottom').height()+'px'});
            this.deviceType('jsToNative','getInfo');
            $('#files').height($('#files').width());
            if(sessionStorage.getItem('backStatus')){
                if(sessionStorage.getItem('backStatus')=== '0'){
                    $('.bottom span').eq(0).addClass('on');
                    $('.main').show();
                    $('.history').hide();
                }else{
                    $('.bottom span').eq(1).addClass('on');
                    $('.main').hide();
                    $('.history').show();
                    $.mobileFeedback.historyRender( JSON.parse(sessionStorage.getItem('historyData')) );
                    $.mobileFeedback.page('page',JSON.parse(sessionStorage.getItem('historyData'))['totalCount']);
                }
            }else{
                $('.bottom span').eq(0).addClass('on');
                $('.main').show();
                $('.history').hide();
            }
        },
        initLayui:function (callback) {
            layui.use(['form','layer'],callback)
        },
        deviceType:function (android,ios) { //判断设备调用方法
            var userAgent = navigator.userAgent.toLowerCase();
            userAgent.match(/android/i) ? WebViewJavaScriptBridge[android]() : window.webkit.messageHandlers[ios]['postMessage'](null)
        },
        renderSelect: function (data) {
            var template = '';
            $.each(data,function (k,v) {
                template += '<li class="clear">' +
'                                <p data-value="'+ v.feedbackType +'">'+ v.typeName +'</p>' +
'                                <span style="background-color: '+ ( $.mobileFeedback.sendData[$.mobileFeedback.id] === Number(k+1) ? '#3399ff' : '') +'"><i class="layui-icon">&#xe605;</i></span>' +
'                            </li>';
            });
            $('.databox .list ul').html(template);
        },
        imgRender:function (data,file) {
            var template = '<div class="imgbox">' +
            '                    <img src="'+ data +'" alt="" file="'+ file +'">' +
            '                    <i class="layui-icon">&#x1006;</i>' +
            '                </div>';
            $('#upload').prepend(template);
            $('.imgbox').height($('#imgbox').height());
        },
        historyAjax:function (data) {
            this.ajaxRequest('/feedback/getHistoryList','post',data,false,function (res) {
                sessionStorage.setItem('historyData',JSON.stringify(res));
                $.mobileFeedback.historyRender(res);
                $.mobileFeedback.page('page',res.totalCount);
            })
        },
        historyRender:function (data) {
            $.mobileFeedback.data.totalCount = data.totalCount;
            var template = '';
            $.each(data.data,function (i,v) {
                var YMD,HM,time;
                time = v.createTime.split(' ');
                YMD = time[0];
                HM = time[1];
                template += '<tr data-id="'+ v.id +'"><a href="">' +
        '                        <td>'+ v.appName +'</td>' +
        '                        <td>'+ v.feedbackType +'</td>' +
        '                        <td>' +
        '                            <p>'+ YMD +'</p>' +
        '                            <p>'+ HM +'</p>' +
        '                        </td>' +
        '                        <td class="replyStatus">'+ v.replyStatus +'</td>' +
        '                        <td class="assessment">' +
        '                        </td></a>' +
        '                    </tr>'
            });
            $('.table .layui-table tbody').html(template);
            $.each(data.data,function (i,v) {
                switch (v.assessment){
                    case 0:
                        $('.table .assessment').html('未评价');
                        break;
                    case 1:
                        $('.table .replyStatus').html('<p style="color: #6dca71;"><i class="layui-icon">&#xe6af;</i><span>满意</span></p>');
                        break;
                    case 2:
                        $('.table .replyStatus').html('<p style="color: red;"><i class="layui-icon">&#xe69c;</i><span>不满意</span></p>');
                        break;
                }
            });
        },
        page:function (obj,count) {
            layui.use(['laypage'],function () {
                var laypage = layui.laypage;
                laypage.render({
                    elem:obj,
                    count:count,
                    groups:5,
                    prev:'<',
                    next:'>',
                    jump:function (obj,first) {
                        console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
                        if(!first){
                            var formdata = new FormData();
                            formdata.append('userId',$.mobileFeedback.data.userData.userId);
                            formdata.append('page',obj.curr-1);
                            formdata.append('pageSize',$.mobileFeedback.data.pageSize);
                            $.mobileFeedback.historyAjax(formdata);
                        }
                    }
                });
            });
        },
        eventListen:function () {

            //图片上传
            $('#files').on('change',function (e) {
                 var file = e.target.files[0];
                 if($.mobileFeedback.sendData.image.length === 3){
                     layui.layer.msg('最多上传3张图片',{icon:2});
                     return;
                 }
                 if(file){
                     var reader = new FileReader();
                     reader.readAsDataURL(file);
                     reader.onload = function () {
                         for (var i=0;i<$.mobileFeedback.sendData.image.length;i++){
                             if(this.result === $.mobileFeedback.sendData.image[i]){
                                 layui.layer.msg('请勿重复上传',{icon:2});
                                 return;
                             }
                         }
                         $.mobileFeedback.imgRender(this.result,file);
                         $.mobileFeedback.sendData.image.push(this.result);
                         console.log($.mobileFeedback.sendData.image);
                         $.mobileFeedback.sendData.images.push(file);
                         $('#files').val('');
                         if($.mobileFeedback.sendData.image.length===3)$('#imgbox').hide();
                     }
                 }
            });

            //点击select
            $('.types').click(function (e) {
                var id = $.mobileFeedback.id = $(this).attr('id');
                $.mobileFeedback.renderSelect($.mobileFeedback.data[id]);
                $('.databox').fadeIn(function () {
                    $('.data .close').css('line-height',$('.data .close').height() + 'px');
                    $('.databox .data').addClass('active');
                });
            });

            //列表点击
            $('.databox .list').on('click','ul li',function (e) {
                $.mobileFeedback.sendData[$.mobileFeedback.id] = $(this).find('p').data('value');
                $('#' + $.mobileFeedback.id).find('p').eq(1).html($(this).find('p').html());
                $(this).parents('.databox').hide();
                $(this).parents('.data').removeClass('active');
            });

            //点击关闭
            $('.databox .close').click(function () {
                $('.databox .data').removeClass('active');
                setTimeout(function () {
                    $('.databox').fadeOut();
                },200)
            });

            //监听字数改变
            $('#content').on('input propertychange',function () {
                $(this).siblings('span').html(200-$(this).val().length)
            });

            //删除图片
            $('#upload').on('click','.imgbox i',function () {
                var index = $(this).parents('.imgbox').index();
                $(this).parents('.imgbox').remove();
                $.mobileFeedback.sendData.image.splice(index,1)
                $.mobileFeedback.sendData.images.splice(index,1)
                $("#imgbox").show();
            });

            //跳转详情
            $('.table .layui-table tbody').on('click','tr',function () {
                location.href = 'feedbackDetail.html?id=' + $(this).data('id') +'&userId='+ $.mobileFeedback.data.userData.userId +'&userType='+ $.mobileFeedback.data.userData.userType
            });

            //提交数据
            $('.main .topTitle div').on('click',function () {
                var fromdata = new FormData();
                $.mobileFeedback.sendData.describe = $('#content').val();
                if($.mobileFeedback.sendData.feedbackType === ''){
                    layui.layer.msg('请选择反馈类型',{icon:2});
                    return;
                }
                if($.mobileFeedback.sendData.describe.length<10){
                    layui.layer.msg('反馈说明不能小于10个字符',{icon:2});
                    return;
                }
                fromdata.append('describe',$.mobileFeedback.sendData.describe);
                fromdata.append('feedbackType',$.mobileFeedback.sendData.feedbackType);
                fromdata.append('userId',$.mobileFeedback.data.userData.userId);
                fromdata.append('appName',$.mobileFeedback.data.userData.appName);
                fromdata.append('packageName',$.mobileFeedback.data.userData.packageName);
                fromdata.append('telephone',$.mobileFeedback.data.userData.telephone);
                fromdata.append('versionCode',$.mobileFeedback.data.userData.versionCode);
                fromdata.append('versionName',$.mobileFeedback.data.userData.versionName);
                fromdata.append('classId',$.mobileFeedback.data.userData.classId);
                fromdata.append('className',$.mobileFeedback.data.userData.className);
                if($.mobileFeedback.sendData.images.length>0){
                    for(var i=0;i<$.mobileFeedback.sendData.images.length;i++){
                        fromdata.append('image[]',$.mobileFeedback.sendData.images[i]);
                    }
                }else {
                    fromdata.append('image[]','');
                }
                var load = layer.load();
                $.mobileFeedback.ajaxRequest('/feedback/saveFeedBack','post',fromdata,true,function (res) {
                    layer.close(load);
                    layui.layer.msg(res.msg,{icon:1});
                    $('#content').val('');
                    $('#feedbackType p').eq(1).html('请选择');
                    $('#upload .imgbox').remove();
                    $.mobileFeedback.sendData.describe = '';
                    $.mobileFeedback.sendData.feedbackType = '';
                    $.mobileFeedback.sendData.image = [];
                    $.mobileFeedback.sendData.images = [];
                    $('#imgbox').show();
                },function (err) {
                    layer.msg(err,{icon:2});
                    layer.close(load);
                });
            });

            //退出反馈
            $('.topTitle > i').click(function () {
                $.mobileFeedback.deviceType('goBack','goBack')
            });

            //history
            $('.bottom').on('click','span',function () {
                var index = $(this).index();
                $('.bottom span').removeClass('on');
                $(this).addClass('on');
                switch (index){
                    case 0:
                        $('.main').show();
                        $('.history').hide();
                        sessionStorage.setItem('backStatus',0);
                        break;
                    case 1:
                        $('.main').hide();
                        $('.history').show();
                        sessionStorage.setItem('backStatus',1);
                        var formdata = new FormData();
                        formdata.append('userId',$.mobileFeedback.data.userData.userId);
                        formdata.append('page',$.mobileFeedback.data.page);
                        formdata.append('pageSize',$.mobileFeedback.data.pageSize);
                        $.mobileFeedback.historyAjax(formdata);
                        break;
                }
            });
        },
        ajaxRequest: function (url,type,data,sync,callback,errorCallback) {
            $.ajax({
                url: url,
                type:type,
                data:data,
                async: sync,
                processData: false,
                contentType: false,
                dataType: "json",
                complete:function (XMLHttpRequest, textStatus) {
                    if(XMLHttpRequest.status===200){
                        if(XMLHttpRequest.responseJSON){
                            callback&&callback(XMLHttpRequest.responseJSON);
                        }else{
                            callback&&callback(JSON.parse(XMLHttpRequest.responseText));
                        }
                    }else{
                        errorCallback && errorCallback(XMLHttpRequest.responseText);
                    }
                }
            })
        }
    }
}();

$.mobileFeedback.init();

//安卓调用 传回需要提交的信息
function putUserInfo(data){
    var obj = JSON.parse(data);
    $.mobileFeedback.data.userData = obj;
}

//安卓调用 传回平台类型,用户类型
function judge(data) {
    var obj = JSON.parse(data);
    for( key in obj ){
        $.mobileFeedback.data.userData[key] = obj[key]
    }
    userType(obj)
}

//ios调用 传回需要提交的信息
function iosPutUserInfo(data) {
    $.mobileFeedback.data.userData = data;
}

function userType(data) {
    if (data.deviceType === 0) { //是平板
        if(data.userType === 'student'){
            $('.selectType > p').hide();
            $('#upload').hide();
            $('#border').hide();
        }
    }
}

